<template>
  <div class="checkout">
    <MyPanel title="确认订单" subTitle="请确认订单信息">
      <div class="checkout-content" v-if="orderItems.length > 0">
        <!-- 收货地址 -->
        <div class="section">
          <h3>收货地址</h3>
          <div class="address-list">
            <div 
              class="address-item" 
              v-for="address in addresses" 
              :key="address.addressId"
              :class="{ selected: selectedAddress && selectedAddress.addressId === address.addressId }"
              @click="selectAddress(address)"
            >
              <div class="address-info">
                <div class="address-header">
                  <span class="recipient">{{ address.recipient }}</span>
                  <span class="phone">{{ address.phone }}</span>
                  <span v-if="address.isDefault" class="default-tag">默认</span>
                </div>
                <div class="address-detail">
                  {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detail }}
                </div>
              </div>
            </div>
            <div class="address-item add-address" @click="showAddAddressModal = true">
              <div class="add-icon">+</div>
              <div>添加新地址</div>
            </div>
          </div>
        </div>
        
        <!-- 商品信息 -->
        <div class="section">
          <h3>商品信息</h3>
          <div class="order-items">
            <div class="order-item" v-for="item in orderItems" :key="item.productId">
              <div class="item-image">
                <img :src="item.product.imageUrl" :alt="item.product.productName" />
              </div>
              <div class="item-info">
                <div class="item-name">{{ item.product.productName }}</div>
                <div class="item-price">¥{{ item.product.price }}</div>
              </div>
              <div class="item-quantity">x {{ item.quantity }}</div>
              <div class="item-total">¥{{ (item.product.price * item.quantity).toFixed(2) }}</div>
            </div>
          </div>
        </div>
        
        <!-- 订单汇总 -->
        <div class="section">
          <h3>订单汇总</h3>
          <div class="order-summary">
            <div class="summary-row">
              <span>商品总价</span>
              <span>¥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <div class="summary-row">
              <span>运费</span>
              <span>¥0.00</span>
            </div>
            <div class="summary-row total">
              <span>总计</span>
              <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
            </div>
          </div>
        </div>
        
        <!-- 提交订单 -->
        <div class="submit-section">
          <button class="submit-btn" @click="submitOrder">提交订单</button>
        </div>
      </div>
      
      <!-- 空订单提示 -->
      <div v-else class="empty-order">
        <div class="empty-icon">
          <i class="iconfont icon-cart"></i>
        </div>
        <p>订单中没有商品</p>
        <router-link to="/" class="go-shopping-btn">
          去逛逛
        </router-link>
      </div>
    </MyPanel>
    
    <!-- 添加收货地址模态框 -->
    <div v-if="showAddAddressModal" class="modal-overlay" @click="closeAddAddressModal">
      <div class="modal-content" @click.stop>
        <h3>添加收货地址</h3>
        <form @submit.prevent="addAddress">
          <div class="form-group">
            <label for="recipient">收货人:</label>
            <input 
              type="text" 
              id="recipient" 
              v-model="addressForm.recipient" 
              placeholder="请输入收货人姓名"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="phone">手机号码:</label>
            <input 
              type="text" 
              id="phone" 
              v-model="addressForm.phone" 
              placeholder="请输入手机号码"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="province">所在省份:</label>
            <input 
              type="text" 
              id="province" 
              v-model="addressForm.province" 
              placeholder="请输入省份"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="city">所在城市:</label>
            <input 
              type="text" 
              id="city" 
              v-model="addressForm.city" 
              placeholder="请输入城市"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="district">所在区县:</label>
            <input 
              type="text" 
              id="district" 
              v-model="addressForm.district" 
              placeholder="请输入区县"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="detail">详细地址:</label>
            <textarea 
              id="detail" 
              v-model="addressForm.detail" 
              placeholder="请输入详细地址"
              required
            ></textarea>
          </div>
          
          <div v-if="addressError" class="error-message">
            {{ addressError }}
          </div>
          
          <div class="modal-actions">
            <button type="button" @click="closeAddAddressModal">取消</button>
            <button type="submit" :disabled="addressLoading">
              {{ addressLoading ? '提交中...' : '确认添加' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from "vue";
import MyPanel from "@/components/MyPanel.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { getUserAddresses, getCartItems, createOrder, syncProductStock, addUserAddress } from "@/api";

export default {
  components: {
    MyPanel
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const addresses = ref([]);
    const selectedAddress = ref(null);
    const orderItems = ref([]);
    const cartItems = ref([]);
    
    // 添加地址表单
    const addressForm = ref({
      recipient: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      detail: ''
    });
    
    // 控制模态框显示
    const showAddAddressModal = ref(false);
    
    // 状态控制
    const addressLoading = ref(false);
    const addressError = ref('');
    
    // 计算总价
    const totalPrice = computed(() => {
      return orderItems.value.reduce((total, item) => {
        return total + (item.product.price * item.quantity);
      }, 0);
    });
    
    // 获取用户地址
    const fetchAddresses = async () => {
      try {
        const res = await getUserAddresses();
        if (res.code === 200) {
          addresses.value = res.data;
          // 设置默认地址
          const defaultAddress = addresses.value.find(addr => addr.isDefault === 1);
          if (defaultAddress) {
            selectedAddress.value = defaultAddress;
          } else if (addresses.value.length > 0) {
            selectedAddress.value = addresses.value[0];
          }
        } else {
          ElMessage.error(res.message || "获取地址列表失败");
        }
      } catch (error) {
        console.error("获取地址列表失败:", error);
        ElMessage.error("获取地址列表失败");
      }
    };
    
    // 获取购物车商品
    const fetchCartItems = async () => {
      try {
        const res = await getCartItems();
        if (res.code === 200) {
          cartItems.value = res.data;
        } else {
          ElMessage.error(res.message || "获取购物车数据失败");
        }
      } catch (error) {
        console.error("获取购物车数据失败:", error);
        ElMessage.error("获取购物车数据失败");
      }
    };
    
    // 准备订单项
    const prepareOrderItems = () => {
      const productId = route.query.productId;
      const quantity = route.query.quantity;
      
      if (productId && quantity) {
        // 立即购买，从商品详情页跳转过来
        // 这里需要获取商品详情
        // 由于立即购买是从推荐商品页面跳转过来，我们需要从路由参数中获取商品信息
        const product = {
          productId: parseInt(productId),
          productName: route.query.productName || "商品名称",
          price: parseFloat(route.query.price) || 0,
          imageUrl: route.query.imageUrl || ""
        };
        
        orderItems.value = [{
          productId: parseInt(productId),
          quantity: parseInt(quantity),
          product: product
        }];
      } else {
        // 从购物车跳转过来
        orderItems.value = cartItems.value.map(item => ({
          productId: item.productId,
          quantity: item.quantity,
          product: item.product
        }));
      }
    };
    
    // 选择地址
    const selectAddress = (address) => {
      selectedAddress.value = address;
    };
    
    // 关闭添加地址模态框
    const closeAddAddressModal = () => {
      showAddAddressModal.value = false;
      // 重置表单
      addressForm.value = {
        recipient: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: ''
      };
      addressError.value = '';
    };
    
    // 添加收货地址
    const addAddress = async () => {
      // 重置错误信息
      addressError.value = '';
      
      // 简单验证表单
      if (!addressForm.value.recipient || !addressForm.value.phone || 
          !addressForm.value.province || !addressForm.value.city || 
          !addressForm.value.district || !addressForm.value.detail) {
        addressError.value = '请填写完整的地址信息';
        return;
      }
      
      addressLoading.value = true;
      
      try {
        const res = await addUserAddress(addressForm.value);
        if (res.code === 200) {
          // 添加成功后重新获取地址列表
          await fetchAddresses();
          closeAddAddressModal();
          // 选择刚添加的地址
          if (addresses.value.length > 0) {
            selectedAddress.value = addresses.value[addresses.value.length - 1];
          }
        } else {
          addressError.value = res.message || '添加地址失败';
        }
      } catch (error) {
        console.error('添加收货地址失败:', error);
        addressError.value = '添加地址失败，请稍后重试';
      } finally {
        addressLoading.value = false;
      }
    };
    
    // 提交订单
    const submitOrder = async () => {
      if (!selectedAddress.value) {
        ElMessage.warning("请选择收货地址");
        return;
      }
      
      if (orderItems.value.length === 0) {
        ElMessage.warning("订单中没有商品");
        return;
      }
      
      // 构造订单数据
      const orderData = {
        orderItems: orderItems.value.map(item => ({
          productId: item.product.productId,
          productName: item.product.productName,
          quantity: item.quantity,
          price: item.product.price
        }))
      };
      
      try {
        // 调用创建订单的API
        const res = await createOrder(orderData);
        if (res.code === 200) {
          ElMessage.success("订单提交成功");
          // 跳转到订单列表页面
          router.push('/orders');
        } else if (res.message && res.message.includes("库存不足")) {
          // 如果是因为库存不足导致的错误，提示用户是否要同步库存
          ElMessageBox.confirm(
            '检测到商品库存可能未同步，是否尝试同步库存并重新提交订单？',
            '库存同步提示',
            {
              confirmButtonText: '同步并重试',
              cancelButtonText: '取消',
              type: 'warning',
            }
          ).then(async () => {
            // 用户选择同步库存
            try {
              // 这里需要调用同步库存的接口
              // 为简单起见，我们假设所有商品都需要同步
              for (const item of orderItems.value) {
                await syncProductStock(item.product.productId);
              }
              ElMessage.success("库存同步完成，请重新提交订单");
            } catch (syncError) {
              console.error("库存同步失败:", syncError);
              ElMessage.error("库存同步失败，请稍后重试");
            }
          }).catch(() => {
            // 用户取消操作
            ElMessage.info("已取消操作");
          });
        } else {
          ElMessage.error(res.message || "订单提交失败");
        }
      } catch (error) {
        console.error("订单提交失败:", error);
        ElMessage.error("订单提交失败，请稍后重试");
      }
    };
    
    onMounted(() => {
      fetchAddresses();
      fetchCartItems().then(() => {
        prepareOrderItems();
      });
    });
    
    return {
      addresses,
      selectedAddress,
      orderItems,
      totalPrice,
      addressForm,
      showAddAddressModal,
      addressLoading,
      addressError,
      selectAddress,
      closeAddAddressModal,
      addAddress,
      submitOrder
    };
  }
};
</script>

<style lang="less" scoped>
@import "@/assets/styles/variables.less";

.checkout {
  .checkout-content {
    .section {
      margin-bottom: 30px;
      
      h3 {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
      }
      
      .address-list {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        
        .address-item {
          width: 250px;
          border: 1px solid #ddd;
          border-radius: 4px;
          padding: 15px;
          cursor: pointer;
          
          &:hover,
          &.selected {
            border-color: @xtxColor;
            background-color: #fff8f0;
          }
          
          .address-info {
            .address-header {
              display: flex;
              justify-content: space-between;
              margin-bottom: 10px;
              
              .recipient {
                font-weight: bold;
              }
              
              .phone {
                color: #999;
              }
              
              .default-tag {
                background-color: @xtxColor;
                color: white;
                font-size: 12px;
                padding: 2px 5px;
                border-radius: 2px;
              }
            }
            
            .address-detail {
              font-size: 14px;
              color: #666;
              line-height: 1.5;
            }
          }
          
          &.add-address {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #999;
            
            .add-icon {
              font-size: 24px;
              font-weight: bold;
              margin-bottom: 5px;
            }
          }
        }
      }
      
      .order-items {
        .order-item {
          display: flex;
          align-items: center;
          padding: 15px 0;
          border-bottom: 1px solid #eee;
          
          .item-image {
            width: 80px;
            height: 80px;
            margin-right: 20px;
            
            img {
              width: 100%;
              height: 100%;
              object-fit: contain;
            }
          }
          
          .item-info {
            flex: 1;
            
            .item-name {
              font-size: 16px;
              margin-bottom: 10px;
            }
            
            .item-price {
              font-size: 18px;
              color: @priceColor;
              font-weight: bold;
            }
          }
          
          .item-quantity {
            width: 60px;
            text-align: center;
            font-size: 16px;
          }
          
          .item-total {
            width: 100px;
            text-align: right;
            font-size: 18px;
            color: @priceColor;
            font-weight: bold;
          }
        }
      }
      
      .order-summary {
        .summary-row {
          display: flex;
          justify-content: space-between;
          padding: 10px 0;
          
          &.total {
            border-top: 1px solid #eee;
            margin-top: 10px;
            font-weight: bold;
            
            .total-price {
              color: @priceColor;
              font-size: 20px;
            }
          }
        }
      }
    }
    
    .submit-section {
      text-align: center;
      padding: 30px 0;
      
      .submit-btn {
        width: 200px;
        height: 50px;
        background-color: @xtxColor;
        color: white;
        border: none;
        border-radius: 4px;
        font-size: 18px;
        cursor: pointer;
        
        &:hover {
          background-color: #b8884d;
        }
      }
    }
  }
  
  .empty-order {
    text-align: center;
    padding: 50px 0;
    
    .empty-icon {
      font-size: 80px;
      color: #ccc;
      margin-bottom: 20px;
    }
    
    p {
      font-size: 18px;
      color: #666;
      margin-bottom: 30px;
    }
    
    .go-shopping-btn {
      display: inline-block;
      padding: 10px 30px;
      background-color: @xtxColor;
      color: white;
      border-radius: 4px;
      text-decoration: none;
      
      &:hover {
        background-color: #b8884d;
      }
    }
  }
  
  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
  }
  
  .modal-content {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    width: 90%;
    max-width: 500px;
    max-height: 90vh;
    overflow-y: auto;
    
    h3 {
      margin-top: 0;
      margin-bottom: 20px;
      text-align: center;
    }
    
    .form-group {
      margin-bottom: 15px;
      
      label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
      }
      
      input, select, textarea {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        box-sizing: border-box;
      }
      
      textarea {
        min-height: 80px;
        resize: vertical;
      }
    }
    
    .error-message {
      color: #f56c6c;
      margin-bottom: 10px;
      padding: 5px;
      background-color: #fef0f0;
      border-radius: 4px;
    }
    
    .modal-actions {
      display: flex;
      justify-content: center;
      gap: 10px;
      margin-top: 20px;
      
      button {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        
        &:first-child {
          background-color: #909399;
          color: white;
        }
        
        &:last-child {
          background-color: #409eff;
          color: white;
        }
        
        &:disabled {
          background-color: #a0cfff;
          cursor: not-allowed;
        }
      }
    }
  }
}
</style>